package com.pingba.executor;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/11/10 0010.
 */
public class MsgCache {
    private Map<Long, Map<String,List>> userMsgInfoMaps = new HashMap<Long, Map<String, List>>();
    private List<Long> keyList = new LinkedList<Long>();
    private static final long MaxUserMsgLength = 200;
    private static MsgCache cache;
    private MsgCache() {

    }

    public static MsgCache getCache() {
        if (cache == null) {
            cache = new MsgCache();
        }
        return cache;
    }

    /**
     * LRU 在用到的时候也需要更新顺序
     * @param userId
     * @return
     */
    public Map<String,List> get(long userId) {
        //更新数据
        if (keyList.indexOf(userId) > -1) {
            keyList.remove(userId);
            keyList.add(userId);
        }

        return userMsgInfoMaps.get(userId);
    }


    /**
     * 控制缓存的数量
     * @param userId
     * @param msgInfoMap
     */
    public void put(long userId, Map<String,List> msgInfoMap) {
        if (userMsgInfoMaps.size() < MaxUserMsgLength) {
            userMsgInfoMaps.put(userId, msgInfoMap);
            if (keyList.indexOf(userId) > -1) {
                keyList.remove(userId);
            }
            keyList.add(userId);
        } else {
            Long eldestUserId = keyList.get(0);
            userMsgInfoMaps.put(userId, msgInfoMap);
            keyList.remove(0);
            userMsgInfoMaps.remove(eldestUserId);
        }
    }
}
